package com.czk.netty.netty.tcp.protocaltcp.server;

import com.czk.netty.netty.tcp.protocaltcp.protocol.MessageProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/24 16:06
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol messageProtocol) throws Exception {
        // 拿到长度
        int len = messageProtocol.getLen();
        // 拿到内容
        byte[] content = messageProtocol.getContent();
        // 服务端接收的信息
        System.out.println("长度=" + len);
        System.out.println("内容=" + new String(content, StandardCharsets.UTF_8));
        System.out.println("服务器接收到的消息包数量=" + (++this.count));

        // 回复消息
        String responseContent = UUID.randomUUID().toString();
        // 长度
        int length = responseContent.getBytes(StandardCharsets.UTF_8).length;
        // 构建包
        MessageProtocol protocol = new MessageProtocol();
        protocol.setContent(responseContent.getBytes(StandardCharsets.UTF_8));
        protocol.setLen(length);
        // 发送
        channelHandlerContext.writeAndFlush(protocol);
    }
}
